package com.hhdys.service;

import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hhdys.dao.MenuTreeMapper;
import com.hhdys.model.MenuTree;
import com.hhdys.model.MenuTreeExample;
import com.hhdys.util.CacheUtil;
import com.hhdys.util.Constant;

import net.sf.ehcache.CacheManager;

@Repository
public class MenuTreeServiceImpl implements MenuTreeService {
	private static final Logger log=Logger.getLogger(MenuTreeServiceImpl.class);
	@Autowired
	private MenuTreeMapper dao;
	@Autowired
	private AccountService accountService;
	@Override
	public List<MenuTree> showAllTrees() {
		return dao.selectByExample(null);
	}
	
	@SuppressWarnings("unchecked")
	private List<MenuTree> showAllDisplayTrees(){
		Object object = CacheUtil.get(Constant.MENUCACHE, Constant.MENUCACHENAME);
		if(object!=null){//从缓存取
			log.info("===从缓存读取菜单树===========");
			return (List<MenuTree>)object;
		}
		MenuTreeExample example=new MenuTreeExample();
		MenuTreeExample.Criteria criteria=example.createCriteria();
		criteria.andIsShowEqualTo(1);
		List<MenuTree> list = dao.selectByExample(example);
		log.info("===从DB读取菜单树===========");
		CacheUtil.save(Constant.MENUCACHE,Constant.MENUCACHENAME,  list);
		return list;
	}

	@Override
	public String showMenus(int userId) {
		Subject curUser=SecurityUtils.getSubject();
		Session session=curUser.getSession();
		List<MenuTree> list = showAllDisplayTrees();
		Set<Integer> userMenus = accountService.selectPageIdsByAccountId((Integer)session.getAttribute("userId"));
		StringBuilder builder = new StringBuilder();
		builder.append("{id : '1',menu : [");
		builder.append(preShowMenu(list, 1, userMenus));
		builder.append("]}");
		return builder.toString();
	}

	private String preShowMenu(List<MenuTree> list, int parentId,
			Set<Integer> userMenus) {
		StringBuilder builder = new StringBuilder();
		for (MenuTree menu : list) {
			if (!userMenus.contains(menu.getId())) {
				continue;
			}
			if (menu.getParentId() == parentId) {
				builder.append("{id:'" + menu.getId() + "',text:'"
						+ menu.getName() + "',href:'" + menu.getUrl() + "',items:["
						+ preShowMenu(list, menu.getId(), userMenus) + "]},");
			}
		}
		if (builder.length() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
		return builder.toString();
	}

	/**
	 * @return the dao
	 */
	public MenuTreeMapper getDao() {
		return dao;
	}

	/**
	 * @param dao
	 *            the dao to set
	 */
	public void setDao(MenuTreeMapper dao) {
		this.dao = dao;
	}

	@Override
	public String getMenuTreesJson() {
		return preJson(showAllTrees(), 0);
	}
	
	private String preJson(List<MenuTree> list, int parentId) {
		StringBuilder builder = new StringBuilder();
		for (MenuTree menu : list) {
			if (menu.getParentId() == parentId) {
				builder.append("{\"name\":\"" + menu.getName()
						+ "\",\"title\":\"" + menu.getName() + "\",\"id\":"
						+ menu.getId() + ",\"open\":\"true\",\"menuUrl\":\""
						+ menu.getUrl() + "\",\"isNew\":\"" + menu.getIsNew()
						+ "\",\"isShow\":\"" + menu.getIsShow()
						+ "\",\"children\":[" + preJson(list, menu.getId())
						+ "]},");
			}
		}
		if (builder.length() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
		return builder.toString();
	}

	@Override
	public boolean addMenu(MenuTree menuTree) {
		CacheUtil.clear(Constant.MENUCACHE, Constant.MENUCACHENAME);
		return dao.insert(menuTree)>0;
	}

	@Override
	public boolean updateMenu(MenuTree menuTree) {
		CacheUtil.clear(Constant.MENUCACHE, Constant.MENUCACHENAME);
		return dao.updateByPrimaryKeySelective(menuTree)>0;
	}

	@Override
	public boolean delMenu(int id) {
		CacheUtil.clear(Constant.MENUCACHE, Constant.MENUCACHENAME);
		return dao.deleteByPrimaryKey(id)>0;
	}

	/**
	 * @return the accountService
	 */
	public AccountService getAccountService() {
		return accountService;
	}

	/**
	 * @param accountService the accountService to set
	 */
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@Override
	public String getMenuName(int menuId) {
		MenuTree menuTree =(MenuTree) CacheUtil.get(Constant.MENUID, String.valueOf(menuId));
		if(menuTree!=null){
			log.debug("使用菜单缓存====");
			return menuTree.getName();
		}
		menuTree=dao.selectByPrimaryKey(menuId);
		if(menuTree!=null){
			CacheUtil.save(Constant.MENUID, String.valueOf(menuId), menuTree);
			return menuTree.getName();
		}
		return "";
	}

}
